package com.applancer.nativecmsflip;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.applancer.adapter.CommentAdapter;
import com.applancer.dataprovider.DataProvider;
import com.applancer.dataprovider.DataType.Type;
import com.applancer.dataprovider.DataUtil;
import com.applancer.model.CommentModel;
import com.applancer.model.GeneralModel;
import com.applancer.parser.GeneralParser;
import com.applancer.provider.ContentManager;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class CommentDialogActivity extends Activity {

	protected TextView titleView;
	protected DataProvider dataprovider;
	protected GeneralParser parser;
	protected String iD;
	protected EditText textArea;
	protected ListView listComment;
	protected CommentAdapter adapter;
	protected List<GeneralModel> listCommentData;
	protected TextView promt_login;
	protected ContentManager contentManager;
	protected ImageView post;
	protected ImageView postFB;
	protected CommentModel tempComment;
	protected String urlpost;

	public static final String MYPREFERENCES = "LoginRef";
	public static final String LOG_STATE = "login_state";

	protected ProgressBar comment_indicator;

	public SharedPreferences sharedpreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_comment_dialog);

		initial();
		execution();

	}

	private void initial() {
		titleView = (TextView) findViewById(R.id.title_comment);
		dataprovider = new DataProvider(this);
		parser = GeneralParser.createInstance(Type.Comment);
		iD = getIntent().getExtras().getString("id");
		urlpost = getIntent().getExtras().getString("urlpost");

		if (listCommentData == null)
			listCommentData = new ArrayList<GeneralModel>();

		listComment = (ListView) findViewById(R.id.comment_list);
		adapter = new CommentAdapter(this, listCommentData);
		promt_login = (TextView) findViewById(R.id.promt_login);
		contentManager = ContentManager.getInstance();
		post = (ImageView) findViewById(R.id.comment_post);
		postFB = (ImageView) findViewById(R.id.commen_post_fb);
		textArea = (EditText) findViewById(R.id.textArea);
		tempComment = new CommentModel();
		comment_indicator = (ProgressBar) findViewById(R.id.comment_indicator);

		sharedpreferences = getSharedPreferences(MYPREFERENCES,
				Context.MODE_PRIVATE);
	}

	private void execution() {
		getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);

		listComment.setAdapter(adapter);

		if (listCommentData.size() == 0)
			getComment();

		if (sharedpreferences.getBoolean(LOG_STATE, false)
				&& contentManager.currentUser != null) {

			promt_login.setText(Html.fromHtml(getString(R.string.login_as)
					+ " <u>" + contentManager.currentUser.getUserName()
					+ "</u>"));
			textArea.setEnabled(true);
			post.setEnabled(true);

		} else {

			promt_login.setText(getString(R.string.promt_login));
			textArea.setEnabled(false);
			post.setEnabled(false);
		}

		post.setOnClickListener(postComment);
		postFB.setOnClickListener(postCommentFB);

		titleView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

	}

	OnClickListener postCommentFB = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String url = DataUtil.servicefb + urlpost;
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setData(Uri.parse(url));
			startActivity(i);
		}
	};

	OnClickListener postComment = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (textArea.getText().toString().equals("")) {

				Toast.makeText(CommentDialogActivity.this,
						getString(R.string.comment_empty), Toast.LENGTH_SHORT)
						.show();

				return;
			}

			tempComment.setAuthorEmail(contentManager.currentUser.getEmail());
			tempComment.setAuthorName(contentManager.currentUser.getUserName());

			tempComment.setContent(textArea.getText().toString());

			Time t = new Time(Time.getCurrentTimezone());
			t.setToNow();
			String date = t.format("%Y-%m-%d  %H:%M:%S");

			tempComment.setDate(date);
			tempComment.setId(listCommentData.size() + "");

			dataprovider.postComment(iD, contentManager.currentUser
					.getUserName(), contentManager.currentUser.getEmail(),
					textArea.getText().toString(), handlerPostcomment);

		}
	};

	private void getComment() {

		comment_indicator.setVisibility(View.VISIBLE);
		dataprovider.getComment(iD, handlerGetcomment);
	}

	AsyncHttpResponseHandler handlerGetcomment = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {
			String result = new String(response);

			listCommentData.clear();

			listCommentData.addAll(parser.parseData(result));
			adapter.notifyDataSetChanged();

			titleView.setText(getString(R.string.title_activity_comment_dialog)
					+ " (" + listCommentData.size() + ")");

		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}

		public void onFinish() {
			comment_indicator.setVisibility(View.GONE);
		};
	};

	AsyncHttpResponseHandler handlerPostcomment = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] response) {
			Toast.makeText(CommentDialogActivity.this, "Success",
					Toast.LENGTH_SHORT).show();

			textArea.setText("");
			listCommentData.add(tempComment);
			adapter.notifyDataSetChanged();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

}
